#include "../include/rnnoise.h"
#include <stdint.h>

void rnnnoise_resample(const int16_t *sourceData, int32_t sampleRate, uint32_t srcSize, int16_t *destinationData,
	int32_t newSampleRate) {
	if (sampleRate == newSampleRate) {
		memcpy(destinationData, sourceData, srcSize * sizeof(int16_t));
		return;
	}
	uint32_t last_pos = srcSize - 1;
	uint32_t dstSize = (uint32_t)(srcSize * ((float)newSampleRate / sampleRate));
	for (uint32_t idx = 0; idx < dstSize; idx++) {
		float index = ((float)idx * sampleRate) / (newSampleRate);
		uint32_t p1 = (uint32_t)index;
		float coef = index - p1;
		uint32_t p2 = (p1 == last_pos) ? last_pos : p1 + 1;
		destinationData[idx] = (int16_t)((1.0f - coef) * sourceData[p1] + coef * sourceData[p2]);
	}
}


float rnnoise_process_frame_16k(DenoiseState *st, short *out, const short *in)
{
	float vad;
	short buf[RNNOISE_FRAME_SIZE];
	rnnnoise_resample(in, 16000, 160, buf, 48000);
	vad = rnnoise_process_frame(st, buf, buf);
	rnnnoise_resample(buf, 48000, 480, out, 16000);
	return vad;
}




float rnnoise_process_frame_8k(DenoiseState *st, short *out, const short *in)
{
	float vad;
	short buf[RNNOISE_FRAME_SIZE];
	rnnnoise_resample(in, 8000, 80, buf, 48000);
	vad = rnnoise_process_frame(st, buf, buf);
	rnnnoise_resample(buf, 48000, 480, out, 8000);
	return vad;
}



